package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import model.CityRegionDAO;


@WebServlet("/CityRegionServlet")
public class CityRegionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	public CityRegionServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String country = request.getParameter("country");
		String region = request.getParameter("region");
		ArrayList<String> results = new ArrayList<String>();
		if (region == null) 
			results = CityRegionDAO.getRegions(country);
		else
			results = CityRegionDAO.getCities(country, region);
		Gson gson = new Gson();
		String[] resultsArray = new String[results.size()];
		for (int i = 0; i < results.size(); i++) {
			resultsArray[i] = results.get(i);
		}
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(new Gson().toJson(resultsArray));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
